package com.ahsjdy.st.stservice.service.impl;

import com.ahsjdy.st.stdao.entity.Merchant;
import com.ahsjdy.st.stdao.entity.Sku;
import com.ahsjdy.st.stdao.mapper.MerchantMapper;
import com.ahsjdy.st.stdao.mapper.SkuMapper;
import com.ahsjdy.stcommon.exception.BizException;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @Description
 * @Author xuetao wang
 * @Date 2020/2/4
 */
@Service
public class CommonService extends BaseService {

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private MerchantMapper merchantMapper;

    @Transactional(rollbackFor = Exception.class)
    public void saveSku(String skuInfo, int merchantId, boolean delFirst) {
        List<Sku> skus = JSON.parseArray(skuInfo, Sku.class);

        if (skus.isEmpty()) {
            return;
        }

        if (delFirst) {
            skuMapper.delSku(merchantId, null, skus.get(0).getSkuType());
        }

        for (Sku sku : skus) {
            sku.setCreateTime(new Date());
            sku.setMerchantId(merchantId);

            if (sku.getSkuType() == null) {
                throw new BizException("保存失败");
            }

            skuMapper.insert(sku);
        }

    }

    public List<Sku> listSku(Integer merchantId, Integer commodityId, Integer skuType) {
        return skuMapper.listSku(merchantId, commodityId, skuType);
    }

    public void delSku(String openId, int skuId) {
        Sku sku = skuMapper.selectByPrimaryKey(skuId);
        if (sku == null) {
            return;
        }


        Merchant merchant = merchantMapper.getByOpenId(openId);
        if (!sku.getMerchantId().equals(merchant.getId())) {
            throw new BizException("无权操作");
        }

        skuMapper.deleteByPrimaryKey(skuId);
    }
}
